package com.hxgz.steel.controller.portal;


import com.hxgz.steel.common.Const;
import com.hxgz.steel.common.ResponseCode;
import com.hxgz.steel.common.ServerResponse;
import com.hxgz.steel.config.WeChatConfig;
import com.hxgz.steel.domain.Order;
import com.hxgz.steel.domain.User;
import com.hxgz.steel.service.OrderService;
import com.hxgz.steel.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.*;

@RequestMapping("weChatBack")
@RestController
@Api(tags = "wechatBackController", description = "前台-个人中心-消息列表")
public class WeChatController {

  @Autowired
  OrderService orderService;

  @Autowired
  WeChatConfig weChatConfig;

  protected static final Logger log = LoggerFactory.getLogger(WeChatController.class);

  /**
   * 微信支付回调
   */
  @RequestMapping("callback.do")
  @ApiOperation("微信支付接口")
  public void orderCallback(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    InputStream inputStream = request.getInputStream();

    //BufferedReader是包装设计模式，性能更搞
    BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
    StringBuffer sb = new StringBuffer();
    String line;
    while ((line = in.readLine()) != null) {
      sb.append(line);
    }
    in.close();
    inputStream.close();
    Map<String, String> callbackMap = WXPayUtil.xmlToMap(sb.toString());
    System.out.println(callbackMap.toString());

    SortedMap<String, String> sortedMap = WXPayUtil.getSortedMap(callbackMap);

    //判断签名是否正确
    if (WXPayUtil.isConrrectSign(sortedMap, weChatConfig.getKey())) {

      if ("SUCCESS".equals(sortedMap.get("result_code"))) {

        String outTradeNo = sortedMap.get("out_trade_no");
        /*VideoOrder dbVideoOrder = videoOrderService.findByOutTradeNo(outTradeNo);*/
        Order order = orderService.getByOrderNo(outTradeNo);
        if (order != null && order.getStatus() == 0) {
          order.setPaymentTime(new Date());
          order.setStatus(1);
          order.setStatusSeller(1);
          order.setPaymentType(0);
          order.setPaymentTime(new Date());
          ServerResponse serverResponse = orderService.updateOrder(order);
          if (serverResponse.getMsg().equals("支付成功")) {
            response.setContentType("text/xml");
            response.getWriter().println("success");
          }
        }
      }
    }
    //都处理失败
    response.setContentType("text/xml");
    response.getWriter().println("fail");
  }

  /**
   * 获取openId
   */
  @RequestMapping(value = "getOpeanId.do", method = RequestMethod.GET)
  public ServerResponse getOpeanId(HttpServletRequest request,
      HttpServletResponse response) {
    String code = request.getParameter("code");
    String openId = WeixinCommenUtil.getOpenId(request, response, code);
    log.info("session中得到的openId值为:>>" + String.valueOf(openId));
    return ServerResponse.createBySuccess("获取成功", openId);
  }


  @RequestMapping(value = "jsPay.do", method = RequestMethod.POST)
  @ApiOperation("小程序支付")
  public ServerResponse jsPay(HttpServletRequest httpServletRequest,
      @ApiParam("订单号") @RequestParam String orderNo) {
    User user = Const.checkUserLogin(httpServletRequest);
    if (user == null) {
      return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),
          ResponseCode.NEED_LOGIN.getDesc());
    }
    String ip = IpUtils.getIpAddr(httpServletRequest);
    try {
      return orderService.jsPay(orderNo, user, ip);
    } catch (Exception e) {
      return ServerResponse.createByErrorMessage("支付失败");
    }
  }


}



